package com.phant.gpsmap;

import java.util.ArrayList;
import java.util.List;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class GPSMap extends MapActivity {

	public class CustomOverlay extends ItemizedOverlay {

		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
		private Context mContext;

		public CustomOverlay(Drawable defaultMarker) {
			super(boundCenter(defaultMarker));
		}

		// Agregando una capa
		public void addOverlay(OverlayItem overlay) {
			mOverlays.add(overlay);
			populate();
		}

		// Creando una capa
		@Override
		protected OverlayItem createItem(int i) {
			return mOverlays.get(i);
		}

		// Esto nos dice cuantas capas hay en total
		@Override
		public int size() {
			return mOverlays.size();
		}

		public CustomOverlay(Drawable defaultMarker, Context context) {
			super(boundCenter(defaultMarker));
			mContext = context;
		}

		

	}

	public class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location location) {
			

			params[0] = location.getLatitude();
			android.util.Log.v("GPS", "LAT "+params[0]);
			params[1] = location.getLongitude();
			android.util.Log.v("GPS", "LONG "+params[1]);
			
			GeoPoint userLocation = new GeoPoint((int) (params[0] * 1E6),
					(int) (params[1] * 1E6));
	        android.util.Log.v("GEOPOINT", "Latitude: "+userLocation.getLatitudeE6() +"  Longitude:  "+userLocation.getLongitudeE6());
			mapController = MyMap.getController();
			mapController.setZoom(ZoomLevel);
			mapController.setCenter(userLocation);
			mapController.animateTo(userLocation);

			myItemizedOverlay.addOverlay(new OverlayItem(userLocation, null,null));
			
			mapOverlays.add(myItemizedOverlay);
			MyMap.invalidate();

			/*
			 * GeoPoint userLocation = new
			 * GeoPoint((int)(location.getLatitude()*
			 * 1E6),(int)(location.getLongitude()* 1E6));
			 * 
			 * mapController.setCenter(userLocation);
			 * mapController.animateTo(userLocation);
			 */

		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

	}

	// Variables
	private double[] params = new double[2];
	private boolean gpsenabled;
	private boolean network_enabled;
	private LocationManager locationManager;
	private MyLocationListener locationListener;
	private MapView MyMap;
	private MapController mapController;
	private int ZoomLevel = 3;
	private CustomOverlay myItemizedOverlay;

	private List<Overlay> mapOverlays;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gpsmap);

		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());

		// Inicializamos el manejador de ubicacion
		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// Definimos el Listener para la ubicacion
		locationListener = new MyLocationListener();

		if (!detectProviders()) {
			AlertDialog.Builder builder = new Builder(this);

			builder.setTitle("Atencion!");

			builder.setMessage("Perdon, pero no podemos obtener su ubicacion");

			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});

			builder.create().show();
		}

		MyMap = (MapView) this.findViewById(R.id.mapView);
		MyMap.setSatellite(false);
		MyMap.setTraffic(true);
		MyMap.setBuiltInZoomControls(true);
		MyMap.invalidate();


		// marcadores
	

		mapOverlays = MyMap.getOverlays();

		myItemizedOverlay = new CustomOverlay(this.getResources().getDrawable(
				R.drawable.pin2), this.getBaseContext()); 
		


	}

	private boolean detectProviders() {
		try {
			gpsenabled = locationManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception e) {
			return false;
		}

		try {
			network_enabled = locationManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception e) {
			return false;
		}

		if (!network_enabled && !gpsenabled) {

			return false;
		}

		if (network_enabled) {
			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
			return true;
		}
		if (gpsenabled) {
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 0, 0, locationListener);
			return true;
		}
		return false;
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

}
